package rpa

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	rpaPb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/rpa"
	"git.myscrm.cn/golang/common/ykenv"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/parnurzeal/gorequest"
	"google.golang.org/grpc"
)

/**
 * @Author: xiuliu
 * @Description:
 * @File:  rpa_config_repository
 * @Version: 1.0.0
 * @Date: 2023/10/31 17:44
 */

var (
	saveProjectUri           = "/v1/rpa/save-data"
	checkProjectDataExistUri = "/v1/rpa/check-data-exist"
)

type RpaRepository struct {
}

func NewRpaRepository() RpaRepositoryIface {
	return &RpaRepository{}
}

//RPA初始化保存配置信息
func (r *RpaRepository) SaveRpaConfigData(ctx context.Context, request *rpaPb.SaveRpaConfigRequest) (*rpaPb.SaveRpaConfigResponse, error) {
	fn := func(ctx context.Context, clientConn *grpc.ClientConn) (interface{}, error) {
		client := rpaPb.NewRpaConfigServiceClient(clientConn)
		resp, err := client.SaveRpaConfig(ctx, request)
		if err != nil {
			return nil, err
		}
		return resp, nil
	}

	resp := &rpaPb.SaveRpaConfigResponse{}
	errs := rpc_client.New(ctx).GetTenantClientConn(constants.MICRO_GFYX_OPPTY_SERVICE).Do(fn, resp, request)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	if resp == nil {
		return nil, errors.New("跟进失败")
	}

	return resp, nil
}

// RPA启动验证
func (r *RpaRepository) RpaStart(ctx context.Context, request *rpaPb.RpaStartRequest) (*rpaPb.RpaStartResponse, error) {
	fn := func(ctx context.Context, clientConn *grpc.ClientConn) (interface{}, error) {
		client := rpaPb.NewRpaStartServiceClient(clientConn)
		resp, err := client.RpaStart(ctx, request)
		if err != nil {
			stark.Logger.Errorf(ctx, "RpaStart 错误，err:", err)
			return nil, err
		}
		return resp, nil
	}
	resp := &rpaPb.RpaStartResponse{}
	errs := rpc_client.New(ctx).GetTenantClientConn(constants.MICRO_GFYX_OPPTY_SERVICE).Do(fn, resp, request)
	if len(errs) > 0 {
		stark.Logger.Errorf(ctx, "RpaStart-GetTenantClientConn 错误，err:", errs)
		return nil, errs[0]
	}
	if resp == nil {
		return nil, errors.New("更新失败")
	}

	return resp, nil
}

type saveProjectResp struct {
	Data      string `json:"data"`
	ErrorCode int    `json:"error_code"`
	Message   string `json:"message"`
	Success   bool   `json:"success"`
}

type checkRpaProjectExistResp struct {
	Data      []string `json:"data"`
	ErrorCode int      `json:"error_code"`
	Message   string   `json:"message"`
	Success   bool     `json:"success"`
}

func (r *RpaRepository) SaveRpaProjectData(ctx context.Context, tenantCode, content string) (bool, error) {
	collect_host := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("collect-servie-host", "")
	if ykenv.IsDevMode() {
		collect_host = "http://127.0.0.1:65499"
	}
	url := collect_host + saveProjectUri
	param := map[string]string{
		"tenant_code": tenantCode,
		"content":     content,
	}

	request := gorequest.New()
	resp := &saveProjectResp{}
	_, body, errs := request.Post(url).
		SendMap(param).
		EndStruct(resp)

	stark.Logger.Infof(ctx, "after-saveRpaProjectData-url: %s, request: %s, body: %+v, errs: %+v", url, param, string(body), errs)
	if errs != nil && len(errs) > 0 {
		return false, errs[0]
	}

	if resp.Success {
		return true, nil
	} else {
		return false, errors.New(resp.Message)
	}
}

func (r *RpaRepository) CheckRpaProjectExist(ctx context.Context, tenantCode string, srcIds []string) ([]string, error) {
	collect_host := stark.Configer.(stark.ApolloConfigerIface).GetStringValue("collect-servie-host", "")
	if ykenv.IsDevMode() {
		collect_host = "http://127.0.0.1:65499"
	}
	url := collect_host + checkProjectDataExistUri
	param := map[string]interface{}{
		"tenant_code": tenantCode,
		"src_id":      srcIds,
	}

	request := gorequest.New()
	resp := &checkRpaProjectExistResp{}
	_, body, errs := request.Post(url).
		SendMap(param).
		EndStruct(resp)

	stark.Logger.Infof(ctx, "after-saveRpaProjectData-url: %s, request: %s, body: %+v, errs: %+v", url, param, string(body), errs)
	if errs != nil && len(errs) > 0 {
		return nil, errs[0]
	}

	if resp.Success {
		return resp.Data, nil
	} else {
		return nil, errors.New(resp.Message)
	}
}
